<template>
  <div class="app-container">
    <!-- 筛选项 -->
    <el-form class="filter" :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="真实姓名">
        <el-input v-model="queryParams.realName" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="员工姓名">
        <el-input v-model="queryParams.staffName" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="员工类型">
        <el-select v-model="queryParams.staffType" placeholder="请选择" clearable>
          <el-option
            v-for="dict in staffTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="员工状态">
        <el-select v-model="queryParams.staffStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in staffStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-row type="flex" justify="end">
        <el-button type="primary" size="mini" @click="onSearch">查询</el-button>
        <el-button size="mini" @click="onSearchClear">清空</el-button>
        <el-button type="primary" size="mini" @click="onStaffAdd">新增员工</el-button>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table class="table" v-loading="loading" :data="tableData" border>
      <el-table-column
        v-for="item in tableColumn"
        :key="item.id"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :min-width="item.minWidth"
        :type="item.type"
        :align="item.align || 'center'"
      >
        <template slot-scope="{ row }">
          <template v-if="item.prop">
            <span>{{ row[item.prop] }}</span>
          </template>

          <template v-if="item.id === 'UNFOLD'">
            <el-table :data="row.subList" border :header-cell-style="{ background: '#f0f8ff' }">
              <el-table-column
                v-for="item1 in subTableColumn"
                :key="item1.id"
                :label="item1.label"
                :prop="item1.prop"
                :width="item1.width"
                :min-width="item1.minWidth"
                :type="item1.type"
                :align="item1.align"
              >
                <template slot-scope="{ row: row1, $index: index1 }">
                  <template v-if="item1.prop">
                    <span>{{ row1[item1.prop] }}</span>
                  </template>

                  <template v-if="item1.id === 'INDEX'">
                    <span>{{ index1 + 1 }}</span>
                  </template>

                  <template v-if="item1.id === 'CHANNEL'">
                    <div>{{ channelTypeTitleOptions[row1.channelType] }}</div>
                    <div>{{ row1.cityName }}</div>
                  </template>

                  <template v-if="item1.id === 'CONFIG'">
                    <template v-if="row1.channelType === 'PUSHCODE'">
                      <div>
                        <el-tag size="small" effect="dark" v-if="row1.pushCode">推广码: {{ row1.pushCode }}</el-tag>
                        <el-tag
                          v-if="row1.pushCodeState"
                          :type="row1.pushCodeState === '0' ? 'success' : 'danger'"
                          size="small"
                          effect="dark"
                        >
                          {{ row1.pushCodeState === "0" ? "有效" : "无效" }}
                        </el-tag>
                      </div>
                      <div v-if="row1.discount">
                        <el-tag size="mini" effect="dark" color="#65cafd">折扣</el-tag>
                        <span>一年: {{ row1.discount.year ? `${row1.discount.year}折` : "--" }}、</span>
                        <span>半年: {{ row1.discount.halfYear ? `${row1.discount.halfYear}折` : "--" }}、</span>
                        <span>季卡: {{ row1.discount.quarter ? `${row1.discount.quarter}折` : "--" }}、</span>
                        <span>月卡: {{ row1.discount.month ? `${row1.discount.month}折` : "--" }}</span>
                      </div>
                      <div v-if="row1.activity">
                        <el-tag type="success" effect="dark" size="mini">满赠</el-tag>
                        <span>一年: {{ row1.activity.year ? `送${row1.activity.year}天` : "--" }}、</span>
                        <span>半年: {{ row1.activity.halfYear ? `送${row1.activity.halfYear}天` : "--" }}、</span>
                        <span>季卡: {{ row1.activity.quarter ? `送${row1.activity.quarter}天` : "--" }}、</span>
                        <span>月卡: {{ row1.activity.month ? `送${row1.activity.month}天` : "--" }}</span>
                      </div>
                    </template>
                    <template v-else>
                      <el-tag
                        v-if="row1.pushCodeState"
                        :type="row1.pushCodeState === '0' ? 'success' : 'danger'"
                        size="small"
                        effect="dark"
                      >
                        {{ row1.pushCodeState === "0" ? "有效" : "无效" }}
                      </el-tag>
                      <template v-if="row1.channelType === 'QWID'">
                        <span>&nbsp;企微手机号: {{ row1.wechatTelSub || "--" }}</span>
                        <span>&nbsp;&nbsp;企微ID: {{ row1.wechatCode || "--" }}</span>
                      </template>

                      <span v-if="row1.channelType === 'GIOCODE'">&nbsp;GIO值: {{ row1.gioCode || "--" }}</span>
                    </template>
                  </template>

                  <template v-if="item1.id === 'CONTROL_TIME'">
                    <div>{{ row1.updateName }}</div>
                    <div>{{ row1.updateTime }}</div>
                  </template>

                  <template v-if="item1.id === 'CONTROL'">
                    <el-button type="text" @click="onChannelEdit(row, row1)">修改</el-button>
                    <el-button
                      type="text"
                      v-if="row1.pushCodeState === '0'"
                      @click="onChannelStatusChange(row.mainId, row1.subId, '1')"
                      :loading="row1.isShowBtnLoading"
                    >
                      禁用
                    </el-button>
                    <el-button
                      type="text"
                      v-else
                      @click="onChannelStatusChange(row.mainId, row1.subId, '0')"
                      :loading="row1.isShowBtnLoading"
                    >
                      启用
                    </el-button>
                    <!-- <el-button type="text" @click="onChannelDel(row.mainId, row1.subId)">删除</el-button> -->
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </template>

          <template v-if="item.id === 'STAFF_INFO'">
            <el-row type="flex" align="middle">
              <el-avatar class="staff-info-avatar" size="large" :src="row.staffAvatarUrl">
                <i class="el-icon-user-solid"></i>
              </el-avatar>
              <div>
                <div>
                  <span>{{ row.staffName }}</span>
                  <span v-if="row.staffType">({{ staffTypeTitleOptions[row.staffType] }})</span>
                </div>
                <div>编号：{{ row.staffNo }}</div>
              </div>
            </el-row>
          </template>

          <template v-if="item.id === 'CONTROL_TIME'">
            <div>{{ row.updateName }}</div>
            <div>{{ row.updateTime }}</div>
          </template>

          <template v-if="item.id === 'STAFF_STATUS'">
            <div>{{ row.staffStatus === "0" ? "在职" : row.staffStatus === "1" ? "离职" : "" }}</div>
          </template>

          <template v-if="item.id === 'CONTROL'">
            <el-button type="text" @click="onStaffEdit(row)">修改</el-button>
            <el-button type="text" @click="onChannelAdd(row)">新增</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 弹窗 -->
    <el-dialog
      :title="dialogConfig[dialogCurrent] ? dialogConfig[dialogCurrent].title : ''"
      :visible.sync="isShowDialog"
      width="1100px"
      :close-on-click-modal="false"
      :append-to-body="true"
      @close="onDialogClose"
      center
    >
      <el-form
        ref="channelForm"
        :model="channelFormData"
        :rules="channelFormRules"
        label-width="120px"
        size="small"
        :inline="true"
      >
        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('STAFF') !== -1">
          <el-row>
            <el-form-item label="头像" prop="staffAvatar">
              <el-upload
                :class="{ hide: isHideUploadEdit }"
                ref="uploadAvatar"
                list-type="picture-card"
                :action="uploadBaseUrl"
                :data="{ filetype: '头像', app: 'shulan', module: '2', sourceKey: '1' }"
                :limit="1"
                :before-upload="onUploadBefore"
                :on-success="onUploadSuccess"
                :on-error="onUploadError"
                :on-exceed="onUploadExceed"
                :on-remove="onUploadRemove"
                accept=".jpg,.jpeg,.png"
                :multiple="false"
                :file-list="avatarPreviewList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-row>
          <el-form-item label="员工姓名" prop="staffName">
            <el-input v-model="channelFormData.staffName" placeholder="请输入" clearable maxlength="10" />
          </el-form-item>
          <el-form-item label="员工类型" prop="staffType">
            <el-select
              v-model="channelFormData.staffType"
              placeholder="请选择"
              :disabled="dialogCurrent && dialogCurrent.indexOf('STAFF_EDIT') !== -1"
            >
              <el-option
                v-for="dict in staffTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="真实姓名" prop="userRealName">
            <el-input v-model="channelFormData.userRealName" placeholder="请输入" clearable maxlength="10" />
          </el-form-item>
          <el-form-item label="微信手机号" prop="staffTel">
            <el-input
              v-model="channelFormData.staffTel"
              placeholder="请输入"
              :maxlength="11"
              clearable
              :disabled="dialogCurrent && dialogCurrent.indexOf('STAFF_EDIT') !== -1"
            />
          </el-form-item>
          <el-form-item label="企微手机号" prop="wechatTel">
            <el-input
              v-model="channelFormData.wechatTel"
              placeholder="请输入"
              :maxlength="11"
              clearable
              :disabled="dialogCurrent && dialogCurrent.indexOf('STAFF_EDIT') !== -1"
            />
          </el-form-item>
          <el-form-item label="客服手机号" prop="serviceTel">
            <el-input v-model="channelFormData.serviceTel" placeholder="请输入" :maxlength="11" clearable />
          </el-form-item>
          <template v-if="dialogCurrent && dialogCurrent.indexOf('STAFF_EDIT') !== -1">
            <el-form-item label="员工状态" prop="staffStatus">
              <el-select v-model="channelFormData.staffStatus" placeholder="请选择" @change="selectStaffStatus">
                <el-option
                  v-for="dict in staffStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="交接员工" prop="transferEmployees" v-if="isEmployees">
              <el-select
                v-model="channelFormData.transferEmployees"
                filterable
                remote
                :disabled="disEmployees"
                placeholder="请输入关键词"
                :remote-method="remoteShopHandler"
                :loading="loading"
                @change="handleChangeShop"
              >
                <el-option
                  v-for="item in restaurants"
                  :key="item.transfSaleMainId"
                  :label="item.userNameTmp"
                  :value="item.transfSaleMainId"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item label="二维码链接" prop="wechatQr">
            <el-input v-model="channelFormData.wechatQr" style="width: 470px" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="后台账号" prop="mgrUserName">
            <el-input v-model="channelFormData.mgrUserName" style="width: 470px" placeholder="请输入" clearable />
          </el-form-item>
          <el-divider v-if="dialogCurrent && dialogCurrent.indexOf('STAFF_ADD') !== -1"></el-divider>
        </template>

        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('CHANNEL') !== -1">
          <el-row>
            <el-form-item label="推广渠道" prop="channelType">
              <el-select
                v-model="channelFormData.channelType"
                placeholder="请选择"
                :disabled="dialogCurrent && dialogCurrent.indexOf('CHANNEL_EDIT') !== -1"
              >
                <el-option
                  v-for="dict in channelTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="cityName">
              <el-select
                v-model="channelFormData.cityName"
                filterable
                placeholder="请搜索"
                :disabled="dialogCurrent && dialogCurrent.indexOf('CHANNEL_EDIT') !== -1"
              >
                <el-option
                  v-for="city in cityOptions"
                  :key="city.code"
                  :label="city.city"
                  :value="city.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </template>

        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('PUSHCODE') !== -1">
          <el-row>
            <el-form-item label="折扣" prop="discount">
              <el-input
                v-for="discountItem in Object.keys(channelFormData.discount)"
                :key="discountItem"
                v-model="channelFormData.discount[discountItem]"
                placeholder="请输入"
                style="width: 200px"
                clearable
                :maxlength="10"
                @input="
                  channelFormData.discount[discountItem] = inputRestrict.onlyNumber(
                    channelFormData.discount[discountItem],
                  )
                "
              >
                <template slot="prepend">
                  {{ dateOptions[discountItem] }}
                </template>
                <span slot="suffix" class="discount">折</span>
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="满送" prop="activity">
              <el-input
                v-for="activityItem in Object.keys(channelFormData.activity)"
                :key="activityItem"
                v-model="channelFormData.activity[activityItem]"
                placeholder="请输入"
                style="width: 200px"
                clearable
                :maxlength="4"
                @input="
                  channelFormData.activity[activityItem] = inputRestrict.onlyNumber(
                    channelFormData.activity[activityItem],
                  )
                "
              >
                <template slot="prepend">
                  {{ dateOptions[activityItem] }}
                </template>
                <span slot="suffix" class="discount">天</span>
              </el-input>
            </el-form-item>
          </el-row>
        </template>

        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('GIOCODE') !== -1">
          <el-row>
            <el-form-item label="GIO值" prop="gioCode">
              <el-input
                v-model="channelFormData.gioCode"
                placeholder="请输入"
                :disabled="dialogCurrent && dialogCurrent.indexOf('CHANNEL_EDIT_GIOCODE') !== -1"
              />
            </el-form-item>
          </el-row>
        </template>

        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('QWID') !== -1">
          <el-row>
            <el-form-item label="企微手机号" prop="wechatTelSub">
              <el-input
                v-model="channelFormData.wechatTelSub"
                placeholder="请输入"
                :maxlength="11"
                clearable
                :disabled="dialogCurrent && dialogCurrent.indexOf('CHANNEL_EDIT_QWID') !== -1"
              />
            </el-form-item>
          </el-row>
        </template>

        <template v-if="dialogConfig[dialogCurrent] && dialogConfig[dialogCurrent].module.indexOf('REMARK') !== -1">
          <el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="channelFormData.remark" placeholder="请输入" style="width: 800px" />
            </el-form-item>
          </el-row>
        </template>

        <el-row type="flex" justify="end">
          <el-form-item>
            <el-button @click="onDialogCancel">取消</el-button>
            <el-button type="primary" @click="submitForm('channelForm')">提交</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import {
  getSaleList,
  addSaleMainInfo,
  addSaleSubInfo,
  updateSaleMainInfo,
  updateSaleSubInfo,
  searchSaleRealName,
} from "@/api/reviewActivities/pushCode";
import CITYS from "@/utils/config/citys";
export default {
  data() {
    let verifys = {
      email: (rule, value, callback) => {
        let rules =
          /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
        if (!rules.test(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      },
      mobile: (rule, value, callback) => {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      },
      sameWechatTel: (rule, value, callback) => {
        if (value === this.channelFormData.wechatTel) {
          callback(new Error("手机号不能与主企微手机号相同"));
        } else {
          callback();
        }
      },
      zh:(rule, value, callback)=>{
         if (!/^[\u4e00-\u9fa5]{0,}$/.test(value)) {
          callback(new Error("真实姓名只能输入汉字"));
        } else {
          callback();
        }
      }
    };
    this.inputRestrict = {
      noPoint(value) {
        if (value.indexOf(".") != -1) {
          let arr = value.split("");
          arr.splice(arr.length - 1);
          let arr2 = arr.join("");
          return arr2;
        }
        return value;
      },
      onlyNumber(value) {
        return value.replace(/[^\d^\.]+/g, "");
      },
    };
    this.staffStatusOptions = [
      { dictValue: "0", dictLabel: "在职" },
      { dictValue: "1", dictLabel: "离职" },
    ];
    this.staffTypeOptions = [
      { dictValue: "OWNPUSH", dictLabel: "面销" },
      { dictValue: "OUTSOURCEPUSH", dictLabel: "地推" },
      { dictValue: "JOINPUSH", dictLabel: "分销" },
      { dictValue: "ONLINEPUSH", dictLabel: "网销" },
      { dictValue: "COOPERATION_HOUSE", dictLabel: "合作房" },
      { dictValue: "WECHATMOMENTS", dictLabel: "朋友圈" },
      { dictValue: "FISSION", dictLabel: "裂变" },
      { dictValue: "OFFICIAL", dictLabel: "官方" },
      { dictValue: "OUTERCHAIN", dictLabel: "外链" },
    ];
    this.tableColumn = [
      { id: "UNFOLD", label: "展开", width: "50", type: "expand" },
      { id: "STAFF_INFO", label: "员工信息", minWidth: "250", align: "left" },
      { id: "PHONE_ID", label: "绑定ID手机号", prop: "staffTel", width: "130" },
      { id: "PHONE_WECHAT", label: "企微手机号", prop: "wechatTel", width: "130" },
      { id: "PHONE_SERVICE", label: "客服手机号", prop: "serviceTel", width: "130" },
      { id: "STAFF_STATUS", label: "状态", width: "130" },
      { id: "QRCODE_WECHAT", label: "企微二维码", prop: "wechatQr", width: "130" },
      { id: "MGR_USER_NAME", label: "后台账号", prop: "mgrUserName", width: "130" },
      { id: "CONTROL_TIME", label: "最后操作时间", width: "150" },
      { id: "CONTROL", label: "操作", width: "130" },
    ];
    this.subTableColumn = [
      { id: "INDEX", label: "序号", width: "50", align: "center" },
      { id: "CHANNEL", label: "推广渠道", width: "130" },
      { id: "CONFIG", label: "配置", width: "500" },
      { id: "REMARK", label: "备注", prop: "remark", maxWidth: "200" },
      { id: "CONTROL_TIME", label: "最后操作时间", width: "150" },
      { id: "CONTROL", label: "操作", width: "150", align: "center" },
    ];
    this.channelTypeOptions = [
      { dictValue: "PUSHCODE", dictLabel: "推广码" },
      { dictValue: "GIOCODE", dictLabel: "gio" },
      // { dictValue: "QWID", dictLabel: "企微手机号" },
    ];
    this.dialogConfig = {
      STAFF_ADD_PUSHCODE: { title: "新增员工信息", module: ["STAFF", "CHANNEL", "REMARK", "PUSHCODE"] },
      STAFF_ADD_GIOCODE: { title: "新增员工信息", module: ["STAFF", "CHANNEL", "REMARK", "GIOCODE"] },
      STAFF_ADD_QWID: { title: "新增员工信息", module: ["STAFF", "CHANNEL", "REMARK", "QWID"] },
      STAFF_EDIT: { title: "修改员工信息", module: ["STAFF"] },
      CHANNEL_ADD_PUSHCODE: { title: "新增渠道", module: ["CHANNEL", "REMARK", "PUSHCODE"] },
      CHANNEL_ADD_GIOCODE: { title: "新增渠道", module: ["CHANNEL", "REMARK", "GIOCODE"] },
      CHANNEL_ADD_QWID: { title: "新增渠道", module: ["CHANNEL", "REMARK", "QWID"] },
      CHANNEL_EDIT_PUSHCODE: { title: "修改渠道", module: ["PUSHCODE", "CHANNEL", "REMARK"] },
      CHANNEL_EDIT_GIOCODE: { title: "修改渠道", module: ["GIOCODE", "CHANNEL", "REMARK"] },
      CHANNEL_EDIT_QWID: { title: "修改渠道", module: ["QWID", "CHANNEL", "REMARK"] },
    };
    this.dateOptions = {
      year: "年卡",
      halfYear: "半年",
      quarter: "季卡",
      month: "月卡",
    };
    this.channelTypeTitleOptions = {
      PUSHCODE: "推广码管理",
      QWID: "企业手机号管理",
      GIOCODE: "GIOCODE管理",
    };
    this.staffTypeTitleOptions = this.staffTypeOptions.reduce((res, item) => {
      res[item.dictValue] = item.dictLabel;
      return res;
    }, {});
    this.uploadBaseUrl = `https://${
      location.hostname === "mgr.shulanfd.com" ? "api" : "api-dev"
    }.shulanfd.com/aist-filesvr-web/api/files`;
    this.cityOptions = CITYS.map((item) => {
      return { ...item, value: item.city.replace("市", "") };
    });
    return {
      isHideUploadEdit: false,
      total: 0,
      queryParams: {
        page: 1,
        pageSize: 10,
        realName: "",
        staffName: "",
        staffType: "",
        staffStatus: "",
      },

      loading: false,
      buttonLoading:false,
      tableData: [],

      isShowDialog: false,
      dialogCurrent: "",
      channelFormRules: {
        staffAvatar: [{ required: true, message: "员工头像不能为空", trigger: "change" }],
        staffName: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
        userRealName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
          { validator: verifys.zh, trigger: "blur" },
        ],
        staffType: [{ required: true, message: "员工类型不能为空", trigger: "change" }],
        staffTel: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: verifys.mobile, trigger: "blur" },
        ],
        wechatTel: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: verifys.mobile, trigger: "blur" },
        ],
        serviceTel: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: verifys.mobile, trigger: "blur" },
        ],
        channelType: [{ required: true, message: "推广渠道不能为空", trigger: "change" }],
        cityName: [{ required: true, message: "城市不能为空", trigger: "change" }],
        gioCode: [{ required: true, message: "GIO值不能为空", trigger: "blur" }],
        wechatTelSub: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: verifys.mobile, trigger: "blur" },
        ],
        transferEmployees: [{ required: true, message: "交接员工不能为空", trigger: "change" }],
      },
      avatarPreviewList: [],
      channelFormData: {
        id: "",
        saleMainId: "",
        staffStatus: "",
        staffAvatar: "",
        staffName: "",
        userRealName: "", //真实姓名
        transferEmployees: "", //交接员工
        transfSaleMainId:'', //交接员工的id
        staffType: "",
        staffTel: "",
        wechatTel: "",
        serviceTel: "",
        wechatQr: "",
        mgrUserName: "", //后台账号
        channelType: "",
        cityName: "",
        remark: "",
        gioCode: "",
        wechatTelSub: "",
        discount: {
          year: "",
          halfYear: "",
          quarter: "",
          month: "",
        },
        activity: {
          year: "",
          halfYear: "",
          quarter: "",
          month: "",
        },
      },
      isEmployees: false, //用来展示交接员工项
      restaurants: [], //销售员列表
      rowInfoTmp: '',
      disEmployees: '', //交接员工默认禁用
    };
  },
  watch: {
    "channelFormData.channelType": function (newValue, oldValue) {
      if (this.isShowDialog) {
        let data = this.dialogCurrent.split("_");
        if (data.indexOf("ADD") !== -1) {
          data[2] = newValue;
          this.dialogCurrent = data.join("_");
        }
      }
    },
    "avatarPreviewList.length": function (newValue, oldValue) {
      this.isHideUploadEdit = newValue >= 1;
    },
  },
  mounted() {
    this.getList();
  },
  methods: {
    onSearch() {
      this.queryParams.page = 1;
      this.getList();
    },
    onSearchClear() {
      this.queryParams = {
        page: 1,
        pageSize: 10,
        realName: "",
        staffName: "",
        staffType: "",
        staffStatus: "",
      };
      this.getList();
    },
    // 获取员工列表
    async getList() {
      let t = this;
      try {
        t.loading = true;
        let { page, pageSize, staffName, staffType, staffStatus, realName } = t.queryParams;
        let res = await getSaleList({
          page: page,
          pageSize: pageSize,
          realName: realName || null,
          userName: staffName || null,
          pushType: staffType || null,
          jobStatue: staffStatus || null,
        });
        if (res && res.data && res.data.isSuccess && res.data.content) {
          let result = res.data.content || {};
          t.total = result.records || 0;
          let list = result.rows.map((item, index) => {
            return t.formatStaffItem(item);
          });
          t.tableData = list;
        }
      } catch (error) {
        console.log(error);
      } finally {
        t.loading = false;
      }
    },
    // 格式化员工列表数据
    formatStaffItem(item) {
      if (!item) {
        return item;
      }
      let subList = [];
      if (item.subCatList && item.subCatList.length) {
        subList = item.subCatList.map((item1, index1) => {
          let discount = null;
          if (item1.discountSet) {
            discount = {
              year: item1.discountSet.YEAR ? Math.floor(item1.discountSet.YEAR * 1000) / 100 : 0,
              halfYear: item1.discountSet.HALFYEAR ? Math.floor(item1.discountSet.HALFYEAR * 1000) / 100 : 0,
              quarter: item1.discountSet.QUARTER ? Math.floor(item1.discountSet.QUARTER * 1000) / 100 : 0,
              month: item1.discountSet.MONTH ? Math.floor(item1.discountSet.MONTH * 1000) / 100 : 0,
            };
          }
          let activity = null;
          if (item1.activityDays) {
            activity = {
              year: item1.activityDays.YEAR || 0,
              halfYear: item1.activityDays.HALFYEAR || 0,
              quarter: item1.activityDays.QUARTER || 0,
              month: item1.activityDays.MONTH || 0,
            };
          }
          return {
            index: index1 + 1,
            pushCodeState: item1.codeState || "",
            pushCode: item1.codeType === "PUSHCODE" ? item1.code : "",
            gioCode: item1.codeType === "GIOCODE" ? item1.code : "",
            wechatCode: item1.codeType === "QWID" ? item1.code : "",
            channelType: item1.codeType || "",
            discount,
            activity,
            remark: item1.subRemark || "",
            updateTime: item1.updateTime ? parseTime(item1.updateTime, "{y}/{m}/{d} {h}:{i}") : "",
            updateName: item1.updateBy || "",
            cityName: item1.city || "",
            wechatTelSub: item1.subMobile || "",
            subId: item1.subId || "",
            isShowBtnLoading: false,
          };
        });
      }
      return {
        mainId: item.id || "",
        staffAvatarUrl: item.headImgUrl || "",
        staffAvatar: item.headImg || "",
        staffName: item.userName || "",
        userRealName: item.userRealName || "",  //真实姓名
        transferEmployees: item.transfer? item.transfer.userName+'/'+item.transfer.userRealName : "",  //交接员工
        transfSaleMainId: item.transfer? item.transfer.id : "",  //交接员工的id
        staffType: item.pushType || "",
        staffNo: item.userNo || "",
        staffTel: item.wxMobile || "",
        wechatTel: item.qwMobile || "",
        serviceTel: item.serviceMobile || "",
        staffStatus: item.jobStatue || "",
        wechatQr: item.qwLinkUrl || "",
        mgrUserName: item.mgrUserName || "",
        updateTime: item.updateTime ? parseTime(item.updateTime, "{y}/{m}/{d} {h}:{i}") : "",
        updateName: item.updateBy || "",
        subList,
      };
    },
    // 新增员工信息
    onStaffAdd() {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.dialogCurrent = "STAFF_ADD_PUSHCODE";
        this.channelFormData = Object.assign({}, this.channelFormData, {
          channelType: "PUSHCODE",
        });
      });
    },
    // 编辑员工信息
    onStaffEdit(row) {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.dialogCurrent = "STAFF_EDIT";
        this.fillFormData(row);
        this.rowInfoTmp = row
        if(this.rowInfoTmp.staffStatus=='1'){
          this.disEmployees = true
          this.isEmployees = true;
        } else{
          this.disEmployees = false
          this.isEmployees = false;
        }
      });
    },
    // 推广渠道新增
    onChannelAdd(row) {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.dialogCurrent = "CHANNEL_ADD_PUSHCODE";
        this.channelFormData = Object.assign({}, this.channelFormData, {
          channelType: "PUSHCODE",
          wechatTel: row.wechatTel,
          saleMainId: row.mainId,
        });
      });
    },
    // 推广渠道编辑
    onChannelEdit(mainRow, subRow) {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.dialogCurrent = `CHANNEL_EDIT_${subRow.channelType}`;
        this.fillFormData(mainRow, subRow);
      });
    },
    // 推广渠道 启用/禁用
    async onChannelStatusChange(mainId, subId, status) {
      let mainIndex = this.tableData.findIndex((item) => item.mainId === mainId);
      let subIndex = this.tableData[mainIndex].subList.findIndex((item) => item.subId === subId);
      try {
        this.tableData[mainIndex].subList[subIndex].isShowBtnLoading = true;
        let res = await updateSaleSubInfo({
          id: subId,
          pushCodeStatue: status,
        });
        if (res && res.data && res.data.isSuccess) {
          this.tableData[mainIndex].subList[subIndex].pushCodeState = status;
        } else {
          this.$message.error("操作失败，请稍后再试...");
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.tableData[mainIndex].subList[subIndex].isShowBtnLoading = false;
      }
    },
    // 提交表单
    submitForm(formName) {
      this.buttonLoading = true
      let t = this;
      t.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let data = {
              id: t.channelFormData.id || "",
              saleMainId: t.channelFormData.saleMainId || "",
              headImg: t.channelFormData.staffAvatar || "",
              userName: t.channelFormData.staffName || "",
              userRealName: t.channelFormData.userRealName || "", //真实姓名
              transferEmployees:t.channelFormData.transferEmployees || "", ////交接员工
              transfSaleMainId: t.channelFormData.transfSaleMainId || "", //交接员工的id
              pushType: t.channelFormData.staffType || "",
              qwMobile: t.channelFormData.wechatTel || "",
              mobile: t.channelFormData.staffTel || "",
              serviceMobile: t.channelFormData.serviceTel || "",
              qwLinkUrl: t.channelFormData.wechatQr || "",
              mgrUserName: t.channelFormData.mgrUserName || "",
              codeType: t.channelFormData.channelType || "",
              city: t.channelFormData.cityName || "",
              subRemark: t.channelFormData.remark || "",
              otherQwMobile: t.channelFormData.wechatTelSub || "",
              gioCode: t.channelFormData.gioCode ? t.channelFormData.gioCode.trim() : "",
              jobStatue: t.channelFormData.staffStatus || "",
              activityDays: {
                YEAR: t.channelFormData.activity.year || "",
                HALFYEAR: t.channelFormData.activity.halfYear || "",
                QUARTER: t.channelFormData.activity.quarter || "",
                MONTH: t.channelFormData.activity.month || "",
              },
              discountSet: {
                YEAR: t.channelFormData.discount.year || "",
                HALFYEAR: t.channelFormData.discount.halfYear || "",
                QUARTER: t.channelFormData.discount.quarter || "",
                MONTH: t.channelFormData.discount.month || "",
              },
            };
            if (t.dialogCurrent.indexOf("STAFF_ADD") !== -1) {//新增员工
              let res = await addSaleMainInfo(data);
              if (res && res.data) {
                if (res.data.isSuccess) {
                  t.onDialogCancel();
                  t.onSearch();
                  scrollTo(0, 0);
                } else {
                  t.errHandler(res.data.errorMessage);
                }
              }
            }
            if (t.dialogCurrent.indexOf("STAFF_EDIT") !== -1) {//修改信息的提交
              let res = await updateSaleMainInfo(data);
              if (res && res.data) {
                if (res.data.isSuccess) {
                  t.onDialogCancel();
                  t.onSearch();
                  scrollTo(0, 0);
                } else {
                  t.errHandler(res.data.errorMessage);
                }
              }
            }
            if (t.dialogCurrent.indexOf("CHANNEL_ADD") !== -1) {
              let res = await addSaleSubInfo(data);
              if (res && res.data) {
                if (res.data.isSuccess) {
                  t.onDialogCancel();
                  t.onSearch();
                  scrollTo(0, 0);
                } else {
                  t.errHandler(res.data.errorMessage);
                }
              }
            }
            if (t.dialogCurrent.indexOf("CHANNEL_EDIT") !== -1) {
              let res = await updateSaleSubInfo(data);
              if (res && res.data) {
                if (res.data.isSuccess) {
                  t.onDialogCancel();
                  t.onSearch();
                  scrollTo(0, 0);
                } else {
                  t.errHandler(res.data.errorMessage);
                }
              }
            }
            this.buttonLoading = false
          } catch (error) {
            console.log(error);
          }
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      try {
        this.$refs[formName].resetFields();
      } catch (error) {}
      this.$refs.uploadAvatar && this.$refs.uploadAvatar.clearFiles();
      this.avatarPreviewList = [];
      this.dialogCurrent = "";
      this.isHideUploadEdit = false;
      this.restaurants = []
      this.channelFormData = Object.assign({}, this.channelFormData, {
        id: "",
        saleMainId: "",
        staffStatus: "",
        staffAvatar: "",
        staffName: "",
        userRealName: "", //真实姓名
        transferEmployees:"", //交接员工
        transfSaleMainId:"", //交接员工的id
        staffType: "",
        staffTel: "",
        wechatTel: "",
        serviceTel: "",
        wechatQr: "",
        mgrUserName: "",
        channelType: "",
        cityName: "",
        remark: "",
        gioCode: "",
        wechatTelSub: "",
        discount: {
          year: "",
          halfYear: "",
          quarter: "",
          month: "",
        },
        activity: {
          year: "",
          halfYear: "",
          quarter: "",
          month: "",
        },
        
      });
    },
    // 取消表单
    onDialogCancel() {
      this.isShowDialog = false;
    },
    // 关闭表单
    onDialogClose() {
      this.resetForm("channelForm");
    },
    onUploadSuccess(res, file, fileList) {
      if (res && res.length) {
        this.channelFormData.staffAvatar = res[0].id;
      } else {
        this.$message.error("图片上传失败");
      }
      this.isHideUploadEdit = fileList.length >= 1;
      this.$refs.channelForm.validateField("staffAvatar");
    },
    onUploadError() {
      this.$message.error("图片上传失败");
    },
    onUploadExceed() {
      this.$message.error("最多只能上传一个头像");
    },
    onUploadBefore(file) {
      let isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      return isJPG;
    },
    onUploadRemove(file, fileList) {
      this.channelFormData.staffAvatar = "";
      this.isHideUploadEdit = fileList.length >= 1;
      this.$refs.channelForm.validateField("staffAvatar");
    },
    fillFormData(mainRow, subRow) {
      if (mainRow) {
        let {
          staffStatus,
          staffAvatar,
          staffAvatarUrl,
          staffName,
          userRealName,//真实姓名
          transferEmployees,  //交接员工
          transfSaleMainId,  //交接员工的id
          staffType,
          staffTel,
          wechatTel,
          serviceTel,
          wechatQr,
          mgrUserName,
          mainId,
        } = mainRow || {};
        this.channelFormData = Object.assign({}, this.channelFormData, {
          saleMainId: mainId,
          staffStatus,
          staffAvatar,
          staffName,
          userRealName, //真实姓名
          transferEmployees,  //交接员工
          transfSaleMainId,  //交接员工的id
          staffType,
          staffTel,
          wechatTel,
          serviceTel,
          wechatQr,
          mgrUserName,
        });
        this.avatarPreviewList.push({ name: "", url: staffAvatarUrl });
      }
      if (subRow) {
        let { gioCode, channelType, discount, activity, remark, cityName, wechatTelSub, subId } = subRow || {};
        this.channelFormData = Object.assign({}, this.channelFormData, {
          id: subId,
          channelType,
          cityName,
          remark,
          gioCode,
          wechatTelSub,
        });
        if (discount) {
          this.channelFormData.discount.year = discount.year || "";
          this.channelFormData.discount.halfYear = discount.halfYear || "";
          this.channelFormData.discount.quarter = discount.quarter || "";
          this.channelFormData.discount.month = discount.month || "";
        }
        if (activity) {
          this.channelFormData.activity.year = activity.year || "";
          this.channelFormData.activity.halfYear = activity.halfYear || "";
          this.channelFormData.activity.quarter = activity.quarter || "";
          this.channelFormData.activity.month = activity.month || "";
        }
      }
    },
    errHandler(code) {
      let msg = {
        5016: "该用户已存在",
        5017: "该企微手机号已存在",
        5001: "微信手机号无法匹配用户",
        5002: "企微手机号无法匹配用户企微ID",
        5003: "企微手机号无法匹配用户企微ID",
        5018: "GIO值已存在",
        5019: "同一城市每种渠道只能创建一条",
      };
      if (code && msg[code]) {
        this.$message.error(msg[code]);
      }
    },
    selectStaffStatus(e) {
      if (e == 1) {
        this.isEmployees = true;
        if(this.rowInfoTmp.staffStatus=='1'){
          this.disEmployees = true
        } else{
          this.disEmployees = false
        }
      } else {
        this.isEmployees = false;
      }
    },

    //交接的员工列表
    remoteShopHandler(query) {
      if (query !== "") {
        this.loading = true;
        searchSaleRealName({ saleRealName: query, page: 1, pageSize: 99 }).then(({ data }) => {
          this.loading = false;
          if (data.isSuccess && data.content) {
            let userTmp = data.content.rows
            this.restaurants = []
            for( let i in userTmp){
              if(userTmp[i].transfSaleMainId!==this.rowInfoTmp.mainId){
                 userTmp[i].userNameTmp = userTmp[i].userName+'/'+ userTmp[i].userRealName
                 this.restaurants.push(userTmp[i])
              }
            }
          }
        });
      } else {
        this.restaurants = [];
      }
    },
    handleChangeShop(e) {
      let item = this.restaurants.find((v) => v.transfSaleMainId == e);
      this.channelFormData.transfSaleMainId = item.transfSaleMainId;
      this.channelFormData.transferEmployees = item.userNameTmp
    },  
  },
};
</script>

<style lang="scss" scoped>
.filter {
  padding-bottom: 20px;
}

.table {
  width: 100%;

  .staff-info-avatar {
    margin-right: 10px;
  }
}

.discount {
  margin-right: 10px;
  line-height: 32px;
  color: #000;
}
</style>

<style lang="scss">
.el-table th.gutter {
  display: table-cell !important;
}
.hide .el-upload--picture-card {
  display: none;
}
</style>
